import logging
import random
from datetime import datetime

from tool import mns_flake, mns_position, mns_math
from log import mns_log
from config import parse
from ship import ship

mns_log.Log.mns_logging()


class Factory:

    def __init__(self, world_x, world_y) -> None:
        self.world_x, self.world_y = world_x, world_y
        self.ship_list = {}
        logging.info("造船工厂已启动")

    def create_ship(self):
        """分组创建船只"""
        begin_time = datetime.now()
        # 船组数量
        group_count = parse.Parse.get_ship_group_count()
        # 船只总数
        ship_count = parse.Parse.get_ship_count()
        # 生成雪花码
        snow_flake = mns_flake.Snowflake(1, 1)
        for i in range(group_count):
            # 获得当前组船只总数
            group_ship_count = parse.Parse.get_ship_count_in_group(i)
            # 获得当前组船只中心位置
            pos_x, pos_y = parse.Parse.get_ship_pos_in_group(i)
            # 获得当前船组方向
            course = parse.Parse.get_ship_course_in_group(i)
            # 获得当前船组速度
            min_speed, max_speed = parse.Parse.get_ship_speed_in_group(i)
            # 获得船只位置
            position = mns_position.Position(group_ship_count, pos_x, pos_y)
            # 当前船只host组
            host_group = parse.Parse.get_host_num_by_ship_group(i)
            for j in range(group_ship_count):
                # 船只位置
                if group_ship_count == 1:
                    ship_pos = pos_x, pos_y
                else:
                    ship_pos = position.generate_pos()[j]
                # 船只名称
                name = snow_flake.generate_id()
                # 船只速度，在最小值和最大值之间随机
                speed = mns_math.mns_round(random.randint(min_speed * 100, max_speed * 100) / 100)
                single_ship = ship.Ship(name, ship_pos[0], ship_pos[1], course, speed, host_group)
                self.ship_list[name] = single_ship
        finish_time = datetime.now()
        total_time = mns_math.mns_round((finish_time - begin_time).total_seconds() * 1000)
        logging.info("船只建造完毕，总数为" + str(ship_count) + "  用时：" + str(total_time) + "ms")
        return self.ship_list

    def get_all_ship(self):
        if len(self.ship_list) != 0:
            return self.ship_list
        else:
            logging.warning("尚未建造船只")
